<template>
  <div class="charts-container">
    <h1 v-if="showTitle">近期天气</h1>
    <div class="charts">
      <div class="top">
        <div
          class="weather-item"
          v-for="item in cityWeatherFourDays"
          :key="item.date"
        >
          <span>{{ item.week }}</span>
          <span>{{ item.date }}</span>
          <span>{{ item.dayweather }}</span>
          <span>风力 {{ item.daypower }}级</span>
        </div>
      </div>
      <div class="bottom">
        <v-chart :option="option" autoresize></v-chart>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useWeatherChart } from '../hooks/useWeatherChart';

const cityWeatherFourDays = ref([]);
const dayTempData = ref([]);
const nightTempData = ref([]);
const { option, renderCharts } = useWeatherChart();

const props = defineProps({
  weatherInFourDays: {
    type: Array,
    required: true,
  },
  showTitle: {
    type: Boolean,
    default: true,
  },
});

// 格式化天气数据
const formatWeatherData = (data) => {
  const day = new Date().getDay();
  const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  data.forEach((item, index) => {
    item.date = item.date.slice(5);
    if (index === 0) {
      item.week = '今天';
    } else if (index === 1) {
      item.week = '明天';
    } else {
      // 确保 week 值在 0-6 范围内
      const weekIndex = parseInt(item.week) % 7;
      item.week = weekday[weekIndex];
    }
  });
};

watch(props, () => {
  cityWeatherFourDays.value = JSON.parse(
    JSON.stringify(props.weatherInFourDays)
  );
  dayTempData.value = cityWeatherFourDays.value.map((item) => item.daytemp);
  nightTempData.value = cityWeatherFourDays.value.map((item) => item.nighttemp);
  formatWeatherData(cityWeatherFourDays.value);
  renderCharts(dayTempData.value, nightTempData.value);
});
</script>

<style lang="scss" scoped>
.charts-container {
  h1 {
    font-size: 16px;
    font-weight: normal;
  }
  .charts {
    margin-top: 20px;
    min-height: 460px;
    background-color: #004e71;
    padding: 35px;
    .top {
      display: flex;
      gap: 10px;
      .weather-item {
        display: flex;
        flex: 1;
        justify-content: space-between;
        flex-direction: column;
        text-align: center;
        gap: 18px;
      }
    }
    .bottom {
      height: 300px;
      margin-top: 20px;
    }
  }
}
</style>